// pages/search/search.js
import request from '../../request/index'
//使用 async await 语法必须引入，固定写法。
import regeneratorRuntime from '../../utils/runtime'
const App = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    inputVal:"",//输入框的值
    sugList:[],//联想建议数据
    keywords:"",//联想关键字输入初始值
    songs:[],//搜索到的相关歌曲
    historyMark:true,//是否显示历史记录
    historyArr:[]
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    const keywords = options.keywords
    if(keywords !== "undefined"){
      this.searchRelated(keywords)
    }
    const historyArr = wx.getStorageSync("search-history") || [];
    this.setData({historyArr})
  },
  //键盘输入时触发
  // timer:null,//防抖
  keywordChange(event) {
    const { value } = event.detail
    this.setData({keywords:value,inputVal:value})
    if(value || !this.data.inputVal){
      this.setData({songs:[]})
    }
    if(!value.trim()){
      this.setData({sugList:[],historyMark:true})
      return
    }   
    // clearTimeout(this.timer)
    //关键字联想
    // this.timer = setTimeout( _ => {
      this.keywordSug(value)
    // },100)
    
  },
  //关键字联想
  async keywordSug(keywords) {
    const result = await request({url:"search/suggest",data:{keywords,type:"mobile"}})
    if(result.code !== 200){
      console.log("获取联想建议失败",result)
      return
    }
    const sugList = result.result.allMatch
    this.setData({sugList})
  },
  //点击搜索键盘搜索按键触发
  clickSearch(event) {
    const {value} = event.detail
    this.addSearchHistory(value)
    this.searchRelated(value)

  },
  //通过关键字搜索相关歌曲
  async searchRelated(keywords) {
    const result = await request({url:"search",data:{keywords,type:1}})
    if(result.code !== 200){
      console.log('搜索相关歌曲失败',result)
      return
    }
    const songs = result.result.songs
    this.setData({songs,keywords:"",historyMark:false,inputVal:keywords})
    this.addSearchHistory(keywords)
  },
  //通过点击历史记录搜索
  clickHistoryKeywords(event) {
    const {keywords} = event.currentTarget.dataset
    this.searchRelated(keywords)
    this.addSearchHistory(keywords)
    this.setData({inputVal:keywords})
  },
  //通过点击搜索建议搜索
  clickSuggestKeywords(event) {
    const {keywords} = event.currentTarget.dataset
    this.searchRelated(keywords)
    this.addSearchHistory(keywords)
    this.setData({inputVal:keywords})
  },
  //音乐播放
  playMusic(event) {
    const {id,index} = event.currentTarget.dataset
    App.globalData.playList = this.data.songs
    App.globalData.musicId = id
    App.globalData.index = index
    wx.navigateTo({url: '/pages/music-play/music-play?id=' + id})
  },
  //添加搜索历史记录
  addSearchHistory(value) {
    let history = wx.getStorageSync("search-history") || [];
    const index = history.findIndex(item => item ===value)
    if(index !== -1){
      history.splice(index,1)
    }
    history.unshift(value)
    wx.setStorageSync("search-history",history);
    this.setData({historyArr:history})
  },
  //删除搜索历史记录
  deleteHistory() {
    wx.showModal({
      title: '确认清空历史记录?',
      showCancel: true,
      cancelText: '取消',
      confirmText: '确定',
      success: (result) => {
        if(result.confirm){
          wx.removeStorageSync("search-history");
          this.setData({historyArr:[]})
        }
      }
    });
  },
  

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})